import React, {Component} from 'react';
import {Dimensions, StyleSheet, Text, View, Image, 
  ScrollView,ImageBackground,
  TouchableOpacity,
} from 'react-native';
import SoundPlayer from 'react-native-sound-player';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';
import MusicScan from '../../component/MusicScan'
import BackButton from '../../component/BackButton';
import NoData from '../../component/NoData';
import { TipModal } from '../../component/Tips';
import {BASEURL} from '../../api/api';
import HeaderTitle from '../../component/HeaderTitle';
import Search from './Search';
let {height, width} = Dimensions.get('window');
var IMG_URL =  BASEURL+'image/showImage?imageName=';
//var height=640,width=320;
// height=738;
// width=392;
var noMore = false;
var pageNo = 0;
var pageSize = 9;
export default class TempMusic extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      keyword:'',
      type:1,  //1-曲库 2-我的音乐
      leftActive:0,
      currMusic:'',
      mp3:'',
      palyId:'',
      leftData:[
			],
			userId: this.props.navigation.getParam('userId'),
      data:[
        // {img:{uri:'http://pic40.photophoto.cn/20160706/0011034331587825_b.jpg'},title: 'Rolling In The Deep',sound:'http://192.168.31.65:8088/music/RollingInTheDeep.mp3'},
        // {img:require('../../images/mine/group2.png'),title: 'Scarlet Letter',sound:'http://192.168.31.65:8088/music/ScarletLetter.mp3'},
        // {img:require('../../images/mine/group3.png'),title: 'Sugar', sound:'http://192.168.31.65:8088/music/sugar.mp3'},
        // {img:require('../../images/mine/group4.png'),title: '这是一个标题'},
      ]
    })
  }
  componentWillMount(){
     this._getTypeList();
  }
  componentWillUnmount(){
    noMore = false;
    pageNo = 0;
    SoundPlayer.stop();
  }
  onHeaderRefresh = () => {
    //alert('header')
  }
  onFooterRefresh = () => {
    if(noMore){
  		return;
    }
    pageNo++;
    if(this.state.type == 1){
      this._getMusicList(1);
    } else if(this.state.type == 2){
      this._getMusicList(2);
    }
    
  	//this.fetchData(pageNo);
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  //获取音乐分类
  _getTypeList(){
    //console.log('url', BASEURL + 'music/musicAllTypeList')
    fetch(BASEURL + 'music/musicAllTypeList')
    .then(res => res.json())
    .then(result => {
      if(result.succ == '1'){
        this.setState({
          leftData: result.list,
          activeTypeId: result.list[0].musicTypeId,
        },()=>{
          if(result.list.length>0){
            //this._getMusicList(result.list[0].musicTypeId)
            this.onFooterRefresh();
          }
        })
      }
    })
    .catch(err => {
      console.log('error',err);
    })
  }
  //获取音乐列表
  _getMusicList(){
    let {type} = this.state;
		//console.log('url', BASEURL + 'music/musicAllTypeList')
		let url =  BASEURL + 'music/getMusicListByTyepId?pageNo='+pageNo+'&pageSize='+pageSize+'&musicTypeId='+this.state.activeTypeId;
		if(type == 2){
			url =  BASEURL + 'music/getMusicListByTyepId?pageNo='+pageNo+'&pageSize='+pageSize+'&userId='+this.state.userId;
		}
    fetch(url)
    .then(res => res.json())
    .then(result => {
      if(result.succ == '1'){
        let data = this.state.data;
        if(pageNo == 1 && type == 1){
          data = [];
				}
				if(type == 2 && pageNo == 1){
					let newData = [];
					if(pageNo == 1){
						newData.push(data[0]);
						data = newData;
					}
				}
				
        if(!result.list.result || result.list.result.length<pageSize ){
          noMore = true
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      }
    })
    .catch(err => {
      console.log('error',err);
    })
  }
  _play(){
    try {
      // play the file tone.mp3
      //SoundPlayer.playSoundFile(this.state.data[0].sound, 'mp3')
      SoundPlayer.playUrl(this.state.data[0].sound)
      // or play from url
      //SoundPlayer.playUrl('https://example.com/music.mp3')
  } catch (e) {
      console.log(`cannot play the sound file`, e)
    }
  }
  _stop(){
    SoundPlayer.stop();
  }
  _playMusic(item){
    console.log('sound--',item.newName)
    if(item.musicId == this.state.palyId){
      SoundPlayer.stop();
      this.setState({
        palyId: '',
      })
      return;
    }
    if(item.newName){
      try {
        // or play from url
        this.setState({
          currMusic: item.musicName,
          mp3: item.newName,
          palyId: item.musicId,
        })
        //console.log('sound',BASEURL+'music/playerMusic?fileName='+item.newName)
        SoundPlayer.playUrl(BASEURL+'music/playerMusic?fileName='+item.newName);
    } catch (e) {
        console.log(`cannot play the sound file`, e)
      }
    }
  }
  //完成音乐选择
  _selectMusic(){
    if(!this.state.mp3){
      this.refs.tipModal._error('您还未选择音乐',1500);
      return;
    }
    const {goBack,state} = this.props.navigation;
    state.params.callback(this.state.mp3);
    this.props.navigation.goBack(); 
  }
  _confirmMusic(item){
    const {goBack,state} = this.props.navigation;
    state.params.callback(item.newName);
    this.props.navigation.goBack(); 
  }
  _leftSelect(index, musicTypeId){
    noMore = false;
    pageNo = 0;
    if(this.state.type == 1){
      this.setState({
        data:[],
        leftActive: index,
        activeTypeId: musicTypeId,
      },()=>{
        this.onFooterRefresh()
      })
    } else {
      
    }
   
  }
  _addMusic(){
    MusicScan.openPicker({
      width: 300,
      height: 400,
      cropping: false
    }).then(result=>{
			console.log('result==',result);
		})
		// ImagePicker.openPicker({
    //   width: 300,
    //   height: 400,
		// 	mediaType: "any",
    //   cropping: false
    // }).then(image => {
    //   console.log(image);
    // });
		/*
    RNFileSelector.Show(
      {
          title: 'Select File',
          onDone: (path) => {
						console.log('file selected: ' + path)
						let ext = path.substring(path.lastIndexOf(".")+1);
						if(ext == 'mp3'){
							this.uploadFile('file://'+path);
						} else {
							this.uploadFile(path);
							//this.refs.tipModal._error('上传失败，请选择 mp3 格式的文件',1500);
						}
						
          },
          onCancel: () => {
              console.log('cancelled')
          }
      }
    )
		*/
	}
	uploadFile(filePath){
    var url = BASEURL+'music/uploadMusic';
    var formData = new FormData();
    var fileName = filePath.substring(filePath.lastIndexOf("/")+1,filePath.length);
    let file = {uri: filePath, type: 'multipart/form-data', name: fileName};
    formData.append("file",file);
    formData.append("userId", this.state.userId);
		this.refs.tipModal._loading();
		console.log('url=',url);
    fetch(url,{
      method:'POST',
      headers:{
				'Content-Type':'multipart/form-data',
      },
      body:formData,
    })
    .then((response) => response.json() )
    .then((result)=>{
			//console.log('responseData',responseData);
			this.refs.tipModal._close();
			noMore = false;
			pageNo = 1;
			this._getMusicList();
			if(result.succ == '1'){
				this.refs.tipModal._success('上传成功');
			}
			
      //this._getUserImageList();
    })
    .catch((error)=>{
			this.refs.tipModal._close();
      console.log('error',error);
    });
  }
  _typeClick(type){
    this.setState({type: type})
  }
  topPress(type){
    noMore = false;
    pageNo = 0;
    this.setState({
      type,
    })
    if(type == 1){
      this.setState({
        data: [],
      },()=>{
        this._getTypeList();
      })
    } else{
    	pageNo = 1;
      this.setState({
        leftActive:0,
        data: [{type: 'add'}],
        leftData: [{typeName: '我的音乐'}]
      },()=>{
				this._getMusicList();
			})
    }
  }
  _renderLeft(){
    let {leftData} = this.state;
    return(
      leftData.map((item, index) => (
        <TouchableOpacity key={index} onPress={()=>{this._leftSelect(index,item.musicTypeId)}} activeOpacity={0.6}
          style={[styles.leftCell,index==this.state.leftActive?styles.leftCellActive:null]}>
          <Text>{item.typeName}</Text>
        </TouchableOpacity>
      ))
    )
  }
  _renderContent(){
    let {data} = this.state;
    return(
      data.map((item, index) => (
        <Cell palyId={this.state.palyId} key={index}   style={{marginBottom:index==data.length-1?0:0}}
        press={()=>this._playMusic(item)} data={item} _confirm={()=>this._confirmMusic(item)}/>
      ))
    )
  }
  _renderItem = ({item,index}) =>{
    //alert(1)
    let data = this.state.data;
    if(item.type && item.type == 'add'){
      return(
        <TouchableOpacity style={styles.cellViewStyle} activeOpacity={0.6} onPress={()=>{this._addMusic()}}>
          <View style={[styles.cellImg, {borderWidth:1,borderColor:'#ccc',backgroundColor:'#eee',justifyContent:'center',alignItems:'center'}]}>
            <Image style={{width:30,height:30}} source={require('../../images/temp/add_img.png')}/>
          </View>
        </TouchableOpacity>
      )
    } else{
			return(
				<Cell palyId={this.state.palyId} key={index}   style={{marginBottom:index==data.length-1?0:0}}
        press={()=>this._playMusic(item)} data={item} _confirm={()=>this._confirmMusic(item)}/>
			)
		}
  }
  _keyExtractor = (item, index) => index.toString();
  _separator = () => {
    return <View style={{height:0,backgroundColor:'#f0f0f0'}}/>;
  }
  _onChange(val){
    this.setState({
      keyword: val,
    })
  }
  _search(){
    noMore = false;
    pageNo = 1;
    this._getMusicList(1);
  }
  render(){
    return(
      <View style={styles.container}>
        <View style={{height:50,flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
          <View style={{flexDirection:'row',alignItems:'center'}}>  
            <BackButton navigation = {this.props.navigation}/>
            <HeaderTitle title='曲库' textColor={this.state.type==1?'#2596ff':'black'} 
              viewColor={this.state.type==1?'#2596ff':'white'}  press={()=>this.topPress(1)}/>
            <View style={{height:30,width:1,backgroundColor:'#aaa'}}></View>
            <HeaderTitle title='我的音乐' textColor={this.state.type==2?'#2596ff':'black'} 
              viewColor={this.state.type==2?'#2596ff':'white'} press={()=>this.topPress(2)}/>
          </View>
          
          <View style={{width:height/5*2}}>
            <Search placeholder='搜索歌曲...'
						search={()=>this._search()} 
						subStyle={{backgroundColor:'#f0f0f0',marginTop:5,paddingRight:5}}
            onChange={(val)=>this._onChange(val)}
            />
          </View>
        </View>
        <View style={styles.currView}>
          <View style={[styles.rowView,{width:'100%',justifyContent:'space-between',alignItems:'center'}]}>
            <View style={{flexDirection:'row',alignItems:'center'}}>
              <Text style={[styles.oneText,{width:100}]}>当前播放：</Text>
              <Image style={styles.musicIcon} source={require('../../images/temp/music_nor.png')}/>
              <Text style={styles.selectMusicText}>{this.state.currMusic}</Text>
            </View>
            <TouchableOpacity onPress={()=>{this._selectMusic()}} style={{height:36,width:36,marginRight:40,
              backgroundColor:'#2596ff',borderRadius:18,justifyContent:'center',alignItems:'center'}}>
              <Text style={{color:'white'}}>确定</Text>
            </TouchableOpacity>
          </View>
          
          {/* <View style={styles.rowView}>
            <TouchableOpacity onPress={()=>this._play()}>
              <Image style={styles.playIcon} source={require('../../images/temp/m_play.png')}/>
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>this._stop()}>
              <Image style={styles.playIcon} source={require('../../images/temp/m_cancel.png')}/>
            </TouchableOpacity>
          </View> */}
        </View>
        <View style={styles.content}>
          <View style={styles.leftView}>
            <ScrollView showsVerticalScrollIndicator={false}>
              {this._renderLeft()}
            </ScrollView>
          </View>
          
          { this.state.data.length == 0? <NoData/>:
            <View style={{flex:1}} >
            <View style={styles.rightView}>
              <RefreshListView
                style={{flex:1,}}
                data={this.state.data}
                keyExtractor={this._keyExtractor}
                renderItem={this._renderItem}
                refreshState={this.state.refreshState}
                onHeaderRefresh={this.onHeaderRefresh}
                onFooterRefresh={this.onFooterRefresh}
                ItemSeparatorComponent={this._separator}
                numColumns={4}
                // 可选
                footerRefreshingText= '数据加载中...'
                footerFailureText = '--数据加载失败--'
                footerNoMoreDataText= '--没有更多了--'
                />
            </View>
          </View>
          }
        </View>
        <TipModal ref="tipModal"/>
      </View>
    )
  }
}
class Cell extends Component{
  render(){
    let img = IMG_URL+this.props.data.musicImg;
    let playImg = require('../../images/temp/icon_play.png');
    let imgStyle;
    let textStyle;
    let  curr = false;
    if(this.props.data.musicId == this.props.palyId){
      playImg = require('../../images/temp/icon_pause.png');
      imgStyle = {width:14,height:14,marginLeft:-2};
      textStyle = {color: '#2596ff'};
      curr = true;
		}
		let _img = {uri: img};
    if(!img){
			_img = require('../../images/temp/no_music.png')
		}
    return(
      <TouchableOpacity style={[styles.cellViewStyle,this.props.style]} activeOpacity={0.9} >
        <ImageBackground style={styles.cellImg} source={ _img}>
          <TouchableOpacity style={styles.playView} onPress={this.props.press}>
            <Image style={[styles.palyIcon,imgStyle]} source={playImg}/>
          </TouchableOpacity>
        </ImageBackground>
        <View style={{alignItems:'center',flexDirection:'row',flexWrap: 'nowrap'}}>
          { !curr ? null :
            <Image style={styles.musicIcon} source={require('../../images/temp/music.png')}/>
          }
          <Text numberOfLines={1} ellipsizeMode='tail' style={[styles.cellText,textStyle]}>{this.props.data.musicName}</Text>
        </View>
        {/* <View style={{flexDirection: 'row',justifyContent:'flex-end'}}>
          <TouchableOpacity onPress={this.props._confirm}>
            <Image resizeMode='contain' style={{width:20,height:16,marginRight:5}} source={require('../../images/temp/icon_confirm.png')}/>
          </TouchableOpacity>
        </View> */}
        
      </TouchableOpacity>
    )
  }
}
let leftWidth = 120;
const styles = StyleSheet.create({
  playView:{
    backgroundColor:'rgba(0,0,0,0.6)',
    borderRadius:20,
    width:30,
    height:30,
    justifyContent:'center',
    alignItems:'center',
  },
   palyIcon:{
    left:1,
    width:20,
    height:20,
  },
  selectMusicText:{
    //color:'#4fb2ff',
    color: '#555'
  },
  playIcon:{
    marginRight:12,
    width:22,
    height:22,
  },
  musicIcon:{
    marginRight:10,
    width:20,
    height:15,
  },
  rowView:{
    flexDirection:'row',
    alignItems:'center',
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'orange',
  },
  oneText:{
    fontSize:14,
    marginLeft:20,
    paddingTop:10,
    paddingBottom:10,
    color:'#555',
  },
  currView:{
    backgroundColor:'#f0f0f0',
    flexDirection:'row',
    justifyContent:'space-between',
  },
  cellViewStyle:{
    marginTop:10,
    marginLeft:5,
    width:(height-leftWidth-40)/4,
    backgroundColor:'#fff',
    paddingBottom:8,
  },
  cellText:{
    padding:5,
    flexWrap:'wrap',
  },
  cellImg:{
    justifyContent:'center',
    alignItems:'center',
    // borderWidth:StyleSheet.hairlineWidth,
    // borderColor:'red',
    width:(height-leftWidth-70)/4,
    height:(height-leftWidth-70)/4*0.7,
  },
  leftCell:{
    padding:15,
    paddingLeft:10,
    paddingRight:10,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#f0f0f0',
    borderLeftColor:'#f0f0f0',
    borderLeftWidth:4,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor:'#ccc',
  },
  leftCellActive:{
    backgroundColor:'#fff',
    borderLeftColor:'#2596ff',
  },
  leftView:{
    // borderWidth:1,
    // borderColor:'gray',
    width:120 ,
  },
  rightView:{
    paddingTop:5,
    paddingLeft: 10,
    //             height-leftWidth-(height-leftWidth-70)
    // paddingRight:10,
    borderWidth:StyleSheet.hairlineWidth,
    borderColor:'green',
    flex:1,
    flexDirection:'row',
    justifyContent:'center',
    flexWrap:'wrap',
  },
  content:{
    flexDirection:'row',
    flex:1,
    // borderWidth:1,
    // borderColor:'red',
  },
  headerText:{
    fontSize:18,
    color:'#000',
    padding:10,
  },
  container: {
    flex: 1
  },
})